package com.linkgap.cloud.service;

import com.linkgap.cloud.entity.Student;
import com.linkgap.cloud.repo.StudentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class StudentService {


    @Autowired
    private StudentRepo studentRepo;

    public List<Student> queryStudentListByClazzIdList(List<Long> clazzIdList) {

        List<Student> res = new ArrayList<>();
        for (int i = 0; i < clazzIdList.size(); i++) {

            List<Student> studentList = studentRepo.findAllByClazzId(clazzIdList.get(i));
            // studentList.iter
            for (Student student : studentList) {
                res.add(student);
            }

        }

        List<Student> studentList = studentRepo.findAllByClazzIdIn(clazzIdList);

       return studentList;
    }


    public List<Student> query() {
        List<Student> list = studentRepo.findAll();
        System.out.println(list);
        return list;
    }

    public Student queryById(Long id) {
        Optional<Student> optional = studentRepo.findById(id);
        Student student = optional.get();
        return student;
    }


    public boolean insertStudent(Student student) {

        String name = student.getName();

        if (name == null) {
            return false;
        }
        Student save = studentRepo.save(student);
        return true;
    }

    /**
     * 前端出入一个名字的字符串，通过str去模糊查询包含此str的所有学生集合
     *
     * @param nameStr
     * @return
     */
    public List<Student> queryByNameLike(String nameStr) {


//        List<Student> all = studentRepo.findAll();


//        studentRepo.findAllByNameContainsAndCnTeacherEquals()

        return studentRepo.findAllByNameContains(nameStr);


    }

    public boolean updateByName(String oldName, String newName) {

        if (oldName == null || newName == null) {
            return false;
        }

        if (oldName.equalsIgnoreCase(newName)) {
            return true;
        }

        List<Student> studentList = studentRepo.findAllByName(oldName);

        if (studentList.size() == 0) {
            return false;
        }

        for (Student student : studentList) {
            student.setName(newName);
        }
        studentRepo.saveAll(studentList);
        return true;
    }
}
